package org.dairy.farms.nandana.core.security.authentication;

import org.dairy.farms.core.UserSession;
import org.dairy.farms.nandana.core.security.userdetails.NandanaUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: gduggira
 * Date: Jun 24, 2011
 * Time: 9:05:28 AM
 */
public class NandanaRequestAwareAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    public void onAuthenticationSuccess(HttpServletRequest request,
            HttpServletResponse response, Authentication authResult)
            throws IOException, ServletException {
        super.onAuthenticationSuccess(request, response, authResult);
        request.getSession().setAttribute("userSession", getUserSession());
    }

    private UserSession getUserSession(){
        UserSession us = new UserSession();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        us.setLoginName(authentication.getName());
        us.setAuthorities(((NandanaUserDetails)authentication.getPrincipal()).getAuthorities());
        us.setPersonId(((NandanaUserDetails)authentication.getPrincipal()).getPersonId());
        return us;
    }
}
